<!--
 * @Descripttion: 新增员工
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-17 21:22:36
 -->
<template>
  <div class="app-container paddingT50">
    <div class="paddingLR20 clearfix">
      <el-card shadow="never" class="oper-btn-card">
        <div class="clearfix">
          <div class="fl">
            <el-button type="primary" size="medium" :loading="btnLoading.save" @click="btnSaveData">保存</el-button>
            <el-button type="default" size="medium" @click="btnCancle">取消</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <el-card shadow="never" class="border-radius-none margin-t2">
      <!-- dataObj: {{ dataObj }} -->
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-position="right"
        label-width="100px"
        size="mini"
      >
        <h3>基础信息</h3>
        <el-divider/>
        <div class="paddingTb20 w600">
          <el-form-item label="所属应用:" prop="relAppId">
            <el-select
              v-model="formData.relAppId"
              filterable
              remote
              reserve-keyword
              placeholder="按所属应用查询"
              :remote-method="remoteMethod"
              :loading="appLoading"
            >
              <el-option
                v-for="item in appOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="`资源名称:`" prop="name">
            <el-input v-model="formData.name" maxlength="64" show-word-limit/>
          </el-form-item>
          <el-form-item :label="`资源编码:`" prop="code">
            <el-input v-model="formData.code" maxlength="40" show-word-limit/>
          </el-form-item>
          <el-form-item :label="`资源图标:`">
            <el-upload
              action=""
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="requestUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </el-form-item>
          <el-form-item label="资源类型:" prop="resourceType">
            <el-radio v-model="formData.resourceType" label="10">菜单</el-radio>
            <el-radio v-model="formData.resourceType" label="20">按钮</el-radio>
            <el-radio v-model="formData.resourceType" label="30">api</el-radio>
          </el-form-item>
          <el-form-item label="访问级别:" prop="accessLevel">
            <el-radio v-model="formData.accessLevel" label="anonymous">匿名访问</el-radio>
            <el-radio v-model="formData.accessLevel" label="after_login">登录后即可访问</el-radio>
            <el-radio v-model="formData.accessLevel" label="permission">拥有权限可访问</el-radio>
          </el-form-item>
          <el-form-item v-if="formData.resourceType=='30'" label="请求方式:" prop="resourceType">
            <el-radio v-model="formData.method" label="GET">GET</el-radio>
            <el-radio v-model="formData.method" label="POST">POST</el-radio>
            <el-radio v-model="formData.method" label="PUT">PUT</el-radio>
            <el-radio v-model="formData.method" label="DETELE">DETELE</el-radio>
            <el-radio v-model="formData.method" label="PATCH">PATCH</el-radio>
          </el-form-item>
          <el-form-item v-if="formData.resourceType!='30'" label="触发后的操作:" prop="action">
            <el-select v-model="formData.action" placeholder="触发后的操作">
              <el-option label="" value=""/>
              <el-option label="新窗口跳转" value="_target"/>
            </el-select>
          </el-form-item>
          <el-form-item label="服务前缀:" prop="serverPrefix">
            <el-input v-model="formData.serverPrefix"/>
          </el-form-item>
          <el-form-item label="URI:" prop="uri">
            <el-input v-model="formData.uri" maxlength="128" show-word-limit/>
          </el-form-item>

        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { create,update, findById } from '@/api/resource/resource.js'
import { findAppByEnableStatus } from '../../../api/application/application'
import { upload } from '../../../api/common/fileupload'

export default {
  name: 'SysResourceAdd',
  mixins: [oftenuse],
  props: {
    operation: {
      type: String,
      default: null,
      validator: (value) => {
        return ['add', 'update'].indexOf(value) !== -1
      }
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      imageUrl: '',
      appOptions: [],
      appLoading: false,
      appLoad: false,
      formData: {
        relAppId: null,
        name: null,
        code: null,
        method: 'GET',
        resourceType: '30',
        accessLevel: 'permission',
        icon: null,
        action: null,
        serverPrefix: null,
        uri: null
      },
      originDataObj: {}, // 编辑状态初始值，用于对比是否修改
      optionsData: {},
      rules: {
        relAppId: [
          { required: true, message: '请选择应用', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入资源名称', trigger: 'blur' },
        ],
        code: [
          { required: false, message: '请输入资源编码', trigger: 'blur' },
        ],
        resourceType: [
          { required: true, message: '请选择资源类型', trigger: 'blur' }
        ],
        accessLevel: [
          { required: true, message: '请选择访问级别', trigger: 'change' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    // 页面初始化数据写在这里
    this.initData()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //  覆盖默认上传行为
    requestUpload(params) {
      const fileData = new FormData()
      fileData.append('file', params.file)
      fileData.append('FileName', params.file.name)
      fileData.append('async', true)
      upload(fileData).then(res => {
        if (res.data.flag) {
          this.formData.icon = res.data.result.relativePath
          this.imageUrl = URL.createObjectURL(params.file)
        }
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.appLoading = true
        setTimeout(() => {
          this.appLoading = false
          this.appOptions = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.appOptions = []
      }
    },
    btnSaveData() {
      this.valiData().then(_ => {
        const params = this.formData
        this.setBtnLoading('save', true)
        this.saveData(params).then(_ => {
          this.setBtnLoading('save', false)
        })
      })
    },
    jump2list() {
      console.log(222222)
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'sysResourceList',
        params: { refresh: true }
      })
    },
    btnCancle() {
      this.jump2list()
    },
    // api
    getRequestData() {
      const params = {}
      return params
    },
    valiData() {
      const v1 = this.handleValid('form')
      return Promise.all([v1])
    },
    saveData(params) {
      this.setBtnLoading('save', true)
      if (!params.id) {
        return create(params).then(res => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) {
            this.$notify.error({ title: '保存异常！', message: res.data.message })
            return
          }
          this.$notify.success({ title: '保存成功！' })
          this.jump2list()
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err.message })
        })
      } else {
        return update(params).then(res => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) {
            this.$notify.error({ title: '修改异常！', message: res.data.message })
            return
          }
          this.$notify.success({ title: '修改成功！' })
          this.jump2list()
        }).catch(err => {
          this.$notify.error({ title: '修改异常！', message: err.message })
        })
      }
    },
    findById(id) {
      findById({ id: id }).then(res => {
        if (res.data.flag) {
          this.formData = res.data.result
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    },
    initData() { // 初始化数据
      console.log('初始化数据')
      this.initOptionsData()
      const id = this.id
      if (id) {
        // 初始化修改时的数据
        this.initUpdateData(id)
      }
    },
    initUpdateData(id) {
      this.findById(id)
    },
    initOptionsData() {
      findAppByEnableStatus({ enableStatus: 'NORMAL' }).then(res => {
        this.appLoad = true
        if (res.data.flag) {
          this.appOptions = res.data.result.map(item => {
            return { value: item.id, label: item.name }
          })
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    }
  }
}
</script>

<style scoped>
.el-divider--horizontal {
  margin: 5px 0;
}
</style>
